from typing import Generic, TypeVar, Optional, List, Dict, Any
from pydantic import BaseModel, Field
from datetime import datetime

# 定义泛型类型变量
T = TypeVar('T')


class ApiResponse(BaseModel, Generic[T]):
    """通用API响应模型"""
    success: bool = Field(description="请求是否成功")
    message: str = Field(description="响应消息")
    data: Optional[T] = Field(default=None, description="响应数据")
    timestamp: Optional[datetime] = Field(default_factory=datetime.now, description="响应时间戳")


class ListResponse(BaseModel, Generic[T]):
    """简单列表响应模型"""
    success: bool = Field(description="请求是否成功")
    data: List[T] = Field(description="响应数据列表")
    total: int = Field(description="总数量")
    timestamp: Optional[datetime] = Field(default_factory=datetime.now, description="响应时间戳")


class ErrorResponse(BaseModel):
    """错误响应模型"""
    success: bool = Field(default=False, description="请求是否成功")
    message: str = Field(description="错误消息")
    error_code: Optional[str] = Field(default=None, description="错误代码")
    details: Optional[Dict[str, Any]] = Field(default=None, description="错误详情")
    timestamp: Optional[datetime] = Field(default_factory=datetime.now, description="响应时间戳")


# 常用的响应类型别名
StandardResponse = ApiResponse[Dict[str, Any]]


# 工具函数
def success_response(
    data: Optional[T] = None,
    message: str = "操作成功",
    **kwargs
) -> ApiResponse[T]:
    """创建成功响应"""
    return ApiResponse[T](
        success=True,
        message=message,
        data=data,
        **kwargs
    )


def error_response(
    message: str = "操作失败",
    error_code: Optional[str] = None,
    details: Optional[Dict[str, Any]] = None,
    **kwargs
) -> ErrorResponse:
    """创建错误响应"""
    return ErrorResponse(
        success=False,
        message=message,
        error_code=error_code,
        details=details,
        **kwargs
    )
